

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using JTC.MiniCommerce.Core;
using JTC.MiniCommerce.Localization;
using JTC.MiniCommerce.Store;
using JTC.MiniCommerce.Store.Web;
using JTC.MiniCommerce.Store.Services.PaymentService;
using SubSonic.Utilities;

namespace JTC.MiniCommerce.Web {
  public partial class cart : System.Web.UI.Page {

    #region Member Variables
    
    private Order order;
    
    #endregion
    
    #region Page Events

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
      try {
        Page.Title = LocalizationUtility.GetText("titleCart");
        order = new OrderController().FetchOrder(WebUtility.GetUserName());
        if (PaymentService.FetchConfiguredPaymentProviders().DefaultProvider == "PayPalProPaymentProvider") {
          pnlExpressCheckout.Visible = true;
        }
        if (!Page.IsPostBack) {
          if (order.OrderId > 0) {
            pnlNoCart.Visible = false;
            orderSummary.Order = order;
            LocalizationUtility.AddLabelText(lblSubTotalTop);
            lblSubTotalAmountTop.Text = StoreUtility.GetFormattedAmount(order.SubTotal, true);
            lbUpdate.Text = LocalizationUtility.GetText("lblUpdate");
          }
          else {
            pnlCart.Visible = false;
            LocalizationUtility.AddLabelText(lblNoCart);
            ProductCollection productCollection;
            if (this.Master.SiteSettings.CollectBrowsingProduct) {
              productCollection = new ProductController().FetchMostPopularProducts();
            }
            else {
              productCollection = new ProductController().FetchRandomProducts();
            }
            catalogList.ProductCollection = productCollection;
          }
        }
      }
      catch (Exception ex) {
        Logger.Error(typeof(cart).Name + ".Page_Load", ex);
        throw;
      }
    }

    /// <summary>
    /// Handles the Click event of the imgPayPal control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void imgPayPal_Click(object sender, EventArgs e) {
      order.PaymentMethod = CreditCardType.PayPal.ToString();
      order.Save(WebUtility.GetUserName());
      string returnUrl = Utility.GetSiteRoot() + "/checkout.aspx";
      string cancelUrl = Utility.GetSiteRoot() + "/default.aspx";
      string url = OrderController.SetExpressCheckout(order, returnUrl, cancelUrl, false);
      Response.Redirect(url, true);
    }

    /// <summary>
    /// Handles the Click event of the btnCheckout control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnCheckout_Click(object sender, EventArgs e) {
      Response.Redirect("~/checkout.aspx");
    }

    /// <summary>
    /// Handles the Click event of the lbUpdate control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void lbUpdate_Click(object sender, EventArgs e) {

      TextBox txtQuantity;
      Label lblOrderItemId;
      Label lblName;

      foreach(RepeaterItem item in orderSummary.Repeater.Items) {
        txtQuantity = item.FindControl("txtQuantity") as TextBox;
        lblOrderItemId = item.FindControl("lblOrderItemId") as Label;
        lblName = item.FindControl("lblName") as Label;
        int orderItemId = 0;
        int quantity = 0;
        if(txtQuantity != null && lblOrderItemId != null) {
          int.TryParse(lblOrderItemId.Text, out orderItemId);
          if(orderItemId > 0) {
            int.TryParse(txtQuantity.Text, out quantity);
            if(quantity > 0) {
              new OrderController().AdjustQuantity(order.OrderId, orderItemId, quantity, WebUtility.GetUserName());
            }
            else {
              new OrderController().RemoveItem(order.OrderId, orderItemId, WebUtility.GetUserName());
            }
          }
        }
      }

      Order modifiedOrder = new OrderController().FetchOrder(WebUtility.GetUserName());
      if(modifiedOrder.OrderItemCollection.Count == 0) {
        Order.Delete(modifiedOrder.OrderId);
      }
      Response.Redirect("~/cart.aspx");
    }
    
    #endregion
    
    #region Methods
    
    #region Protected

    /// <summary>
    /// Gets the formatted amount.
    /// </summary>
    /// <param name="pricePaid">The price paid.</param>
    /// <returns></returns>
    protected string GetFormattedAmount(string pricePaid) {
      return StoreUtility.GetFormattedAmount(pricePaid, true);
    }
    
    #endregion
    
    #endregion
    
  }
}
